package com.cicoding.config;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName WebSocket
 * @Description WebSocket服务
 * @Author WTT
 * @Date 2023/5/4 9:41
 * @Version 1.0
 **/
@ServerEndpoint(value = "/websocket/{userId}")
//主要是将目前的类定义成一个websocket服务器端, 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
@Component
@Data
@Slf4j
public class WebSocket {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, WebSocket> webSocketSet = new ConcurrentHashMap<>();

    //指定的sid，具有唯一性
    private static String sid = "";

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    public static ConcurrentHashMap<String, WebSocket> getWebSocketSet() {
        return webSocketSet;
    }

    public static void setWebSocketSet(ConcurrentHashMap<String, WebSocket> webSocketSet) {
        WebSocket.webSocketSet = webSocketSet;
    }


    /**
     * 连接建立成功调用的方法
     *
     * @param session 会话
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) throws Exception {
        this.session = session;
        sid = userId;
        webSocketSet.put(sid, this);     //加入set中
        log.info("【websocket消息】有新的连接，总数为:" + webSocketSet.size());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("参数信息：{}", message);
        //群发消息
        try {
            log.info("【收到】，客户端{}的信息:{}", session, message);
            sendMessage(message);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("参数有误");
            sendMessage("参数有误！！！");

        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        if (session != null) {
            try {
                session.close();
                log.info("【websocket消息】关闭了一个连接，总数为:" + webSocketSet.size());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时调用
     *
     * @param session 会话
     * @param error   错误信息
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("连接异常！");
        error.printStackTrace();
    }

    /**
     * 发送信息
     *
     * @param message 消息
     */
    public void sendMessage(String message) throws IOException {
        // 防止频繁断连问题引发的报错： The WebSocket session [3d] has been closed and no method (apart from close()) may be called on a closed session
        if (this.session.isOpen()) {
            this.session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 自定义消息推送、可群发、单发
     *
     * @param message 消息
     */
    public static boolean sendInfo(String message, String userId) {
        log.info("给用户" + userId + "发送消息：" + message);
        if (webSocketSet.get(userId) != null) {
            if (!sid.equals(userId)) {
                return false;
            } else {
                try {
                    webSocketSet.get(userId).sendMessage(message);
                    return true;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 自定义消息推送、可群发、单发
     *
     * @param message 消息
     */
    public static boolean sendAllInfo(String message, List<String> userIds) {
        log.info("给用户" + userIds.toString() + "发送消息：" + message);
        for (int i = 0; i < userIds.size(); i++) {
            if (webSocketSet.get(userIds.get(i)) != null) {
                if (!sid.equals(userIds.get(i))) {
                    return false;
                } else {
                    try {
                        webSocketSet.get(userIds.get(i)).sendMessage(message);
                        return true;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return false;
    }
}



